<?php

namespace WeChat\Controller;

use Common\Model\MemberModel;
use Think\Log;

class OrderController extends BaseController {

    function _initialize() {
        parent::_initialize();
        $this->uid = $this->login();
      //   $this->uid = 57;
    }

    /*
     * 订单状态处理
     */

    public function deal() {

        $type = I('param.type');

        $id = I('param.order_id');

        if (empty($id)) {

            $this->error('没有找到订单！');
        }


        $map['id'] = $id;

        $order = M('Order')->where('id =' . $id)->find();

        switch ($type) {

            case 'ocancle':
                if (($order['pay_status'] < 2) and ( $order['status'] < 2)) {

                    $row = M('Order')->where($map)->setField('status', 2);

                    if ($row) {

                        $this->success('订单已取消！');
                    } else {

                        $this->error('订单取消失败！');
                    }
                } else {
                    $this->error('这个订单不能取消！');
                }

                break;

            case 'odel':
                if (($order['status'] == 2) and ( $order['pay_status'] < 2)) {

                    $row = M('Order')->where($map)->setField('status', 3);

                    if ($row) {

                        $this->success('订单已删除！');
                    } else {

                        $this->error('订单删除失败！');
                    }
                } else {
                    $this->error('这个订单不能删除！');
                }

                break;

            case 'oshouhuo':
                if (($order['status'] == 1) and ( $order['pay_status'] == 2) and ( $order['send_status'] == 1)) {

                    $row = M('Order')->where($map)->setField('send_status', 2);

                    if ($row) {

                        $this->success('订单收货成功！');
                    } else {

                        $this->error('订单收货失败！');
                    }
                } else {
                    $this->error('这个订单不能收货！');
                }

                break;

            case 'otuihuo':
                if (($order['send_status'] >= 0) and ( $order['pay_status'] == 2)) {

                    $row = M('Order')->where($map)->setField('status', 4);

                    if ($row) {

                        $this->success('订单确认退货！');
                    } else {

                        $this->error('订单退货失败！');
                    }
                } else {
                    $this->error('这个订单不能退货！');
                }

                break;
        }
    }

    /*
     * 提交订单
     */

    public function make() {

        if (IS_POST) {
            $order_model = D('Order');
            $goods_model = D('Goods');

            #检测商品信息
            $products_id = I("post.pid");
            $products_num = I("post.pnum");

            if (empty($products_id) && empty($products_num)) {

                $this->error('请重新添加产品！', U("WeChat/Cart/index"));
            }

            $_POST['ids'] = implode(",", $products_id); //商品ID
            $_POST['pnum'] = $this->cart->getNum(); //购物车商品总数量
            // 根据当前最大订单ID生成新order_no
            $max_order_id = $order_model->max('id');
            $max_order_id = $max_order_id ? $max_order_id : 0;
            $order_no = order_number_2($max_order_id);

            $_POST['order_no'] = $order_no;

            //补充订单信息
            $remark = str_replace(' ', '', I('post.remark'));

            if ($remark == '买家留言...') {

                $_POST['remark'] = '';
            }

            $_POST['user_id'] = is_login_wechat();   //用户ID

            $_POST['overtime'] = NOW_TIME + 25920;   //订单过期时间 下单后 三天

            $cart_goods = $_SESSION['cart'];
            
            $total = 0;
            foreach ($cart_goods as $k => $v) {
                $item = $v['price'] * $v['num'];
                $total += $item;
            }
            $_POST['total'] = $total;
            $data = $order_model->create();   //创建订单数据信息

            $user_model = new MemberModel();

            if ($data) {

                $order_id = $order_model->add();

                if ($order_id) {

                    $orderGoods = array();

                    $map['id'] = array('in', implode(',', $products_id));

                    $goods = $goods_model->where($map)->select();

                    foreach ($goods as $k => $item) {

                        //查询购物车中此商品信息
                        $cg = $this->cart->getItem($item['id']);

                        $item['price'] = $user_model->getPrice($item['price'], $this->uid);

                        $orderGoods[] = array(
                            'order_id' => $order_id,
                            'order_no' => $order_no,
                            'goods_id' => $item['id'],
                            'category' => $item['category'],
                            'title' => $item['title'],
                            'price' => $item['price'],
                            'original_price' => $item['original_price'],
//                            'commission' => $item['commission'],
                            'commission' => $item['price'],
                            'pv' => $item['pv'],
                            'cover' => $item['cover'],
                            'detail' => $item['detail'],
                            'count' => $cg['num'],
                            'create_time' => NOW_TIME
                        );
                    }
               
                    $od = M("OrderGoods")->addAll($orderGoods);

                    if ($od) {
                        $this->cart->clear();
                        $this->success('订单提交成功！', U("WeChat/Pay/index", array("id" => $order_id)));
                    } else {
                        $order_model->delete($order_id);
                        $this->error('下单失败', U("WeChat/Cart/index"));
                    }
                } else {

                    $this->error('下单失败', U("WeChat/Cart/index"));
                }
            } else {

                $this->error($order_model->getError(), U("WeChat/Order/make"));
            }
        } else {
          //  $this->login();
            #获取微信共享地址参数
            $timestamp = time();    //时间戳

            $nonceStr = rand(100000, 999999);  //随机字符串

            Log::write('__SELF__:' . C('WEB_SITE_DOMAIN') . __SELF__);
            $params = array();

            $params['appid'] = $this->appid;
            $params['url'] = C('WEB_SITE_DOMAIN') . __SELF__;
            $params['timestamp'] = "$timestamp";
            $params['noncestr'] = "$nonceStr";
            $params['accesstoken'] = $this->access_token;
            $addrSign = $this->wechat->genSha1Sign($params);

            Log::write('调用微信地址信息data:' . json_encode($params));
            Log::write('addrSign签名:' . $addrSign);

            $this->assign("timestamp", $timestamp);
            $this->assign("nonceStr", $nonceStr);
            $this->assign("appid", $this->appid);
            $this->assign("addrSign", $addrSign);
            $this->assign("cart_list", $this->cart->getCart());
            $this->assign("cart_price", $this->cart->getPrice());
            $this->assign("cart_pv", $this->cart->getPrice('pv'));
            $this->display();
        }
    }

}
